<!--
/**
* @description 方案管理
* @author wind-lc
* @date 2020-05-14
*/
-->
<template>
  <div>
    <!-- 顶部控件 -->
    <a-form-model :model="searchForm"
                  class="index-search-form-model"
                  ref="searchForm"
                  layout="inline"
    >
      <a-form-model-item label="方案名称"
                         prop="name">
        <a-input v-model="searchForm.name"
                 placeholder="请输入方案名称">
        </a-input>
      </a-form-model-item>
      <a-form-model-item label="应急类型"
                         prop="emergencyType">
        <a-select v-model="searchForm.emergencyType">
          <a-select-option v-for="(item,index) in emergencyTypeList"
                           :key="index"
                           :value="item.value">{{item.name}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="起止时间"
                         prop="fromTo">
        <a-range-picker v-model="searchForm.fromTo"></a-range-picker>
      </a-form-model-item>
      <a-form-model-item label="创建时间"
                         prop="createTime">
        <a-range-picker v-model="searchForm.createTime"></a-range-picker>
      </a-form-model-item>
      <a-form-model-item label="响应类型"
                         prop="responseType">
        <a-select v-model="searchForm.responseType"
                  placeholder="请选择响应类型">
          <a-select-option v-for="(item,index) in responseTypeList"
                           :key="index"
                           :value="item.value">{{item.name}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="执行状态"
                         prop="status">
        <a-select v-model="searchForm.status"
                  placeholder="请选择执行类型">
          <a-select-option v-for="(item,index) in statusList"
                           :key="index"
                           :value="item.value">{{item.name}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 24 }"
                         class="top-widget-btn">
        <a-button type="primary"
                  icon="search"
                  shape="round"
                  @click="searchData">查询</a-button>
        <a-button icon="retweet"
                  shape="round"
                  @click="resetSearch">重置</a-button>
      </a-form-model-item>
    </a-form-model>
    <!-- 顶部控件 -->
    <div class="page">
      <form-loading :formLoadingVisible="!pageReady"></form-loading>
      <div class="table-opt-btns">
        <a-button :disabled="!isSelecte"
                @click="batchRemove">批量删除</a-button>
      </div>
      <!-- 表格 -->
      <a-table rowKey="id"
               :columns="columns"
               :dataSource="data"
               :rowSelection="{selectedRowKeys: selectedRowKeys,onChange: selectedRowChange}"
               bordered
               :customRow="tableCustomRow"
               :loading="tableLoading"
               @change="tableChange"
               :pagination="pagination">
        <div slot="statusCustom"
             slot-scope="text,record,index"
             class="tabe-switch">
             <a-popconfirm  title="确定要切换状态吗"
                            @confirm="upStatus(text, record, index)"
                            okText="是"
                            cancelText="否"
            >
              <a-switch v-if="statusList.length"
                        :checked="(statusList.length && record.status === statusList[0].value) || false"
                        :checked-children="statusList.length && statusList[0].name"
                        :un-checked-children="statusList.length && statusList[1].name"
              />
            </a-popconfirm>
        </div>
        <div slot="operation"
             slot-scope="text,record"
             class="tabe-button">
          <a-button size="small"
                    icon="edit"
                    @click="edit(record)"
                    type="primary">
            编辑
          </a-button>
        </div>
      </a-table>
      <!-- 表格 -->
      <!-- 查看方案 -->
      <scheme-view :viewVisible="viewVisible"
                   :viewId="viewId"
                   @handleVisible="handleViewVisible"></scheme-view>
      <!-- 查看方案 -->
    </div>
  </div>
</template>
<script>
import { FormModel, Input, Select, DatePicker, Button, Table, Popconfirm, Switch } from 'ant-design-vue'
import SchemeView from './components/SchemeView'
import { getDictData } from '@/request/api/common'
import { getPageHnPlan, deleteBatch, updateStatus } from '@/request/api/emergencyControl/schemeManagement'
export default {
  name: 'schemeManagement',
  components: {
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    ASelect: Select,
    ASelectOption: Select.Option,
    ARangePicker: DatePicker.RangePicker,
    AButton: Button,
    ATable: Table,
    SchemeView,
    APopconfirm: Popconfirm,
    ASwitch: Switch
  },
  data () {
    return {
      // 页面完成
      pageReady: false,
      // 数据字典
      dataDictionary: {},
      // 顶部搜索表单
      searchForm: {
        name: '',
        emergencyType: '',
        fromTo: [],
        createTime: [],
        responseType: '',
        status: ''
      },
      // 应急类型列表
      emergencyTypeList: [],
      // 响应类型
      responseTypeList: [],
      // 执行状态
      statusList: [],
      // 角色表头
      columns: [
        {
          title: '序号',
          align: 'center',
          ellipsis: true,
          width: 80,
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '方案名称',
          align: 'center',
          ellipsis: true,
          dataIndex: 'name'
        },
        {
          title: '创建时间',
          align: 'center',
          ellipsis: true,
          dataIndex: 'createTime'
        },
        {
          title: '应急类型',
          align: 'center',
          ellipsis: true,
          dataIndex: 'contingencyType',
          customRender: (text, record, index) => {
            let txt = ''
            this.dataDictionary['W-067'].forEach(el => {
              if (text === el.value) {
                txt = el.name
              }
            })
            return txt
          }
        },
        {
          title: '状态',
          align: 'center',
          ellipsis: true,
          dataIndex: 'status',
          // customRender: (text, record, index) => {
          //   let txt = ''
          //   this.dataDictionary['W-069'].forEach(el => {
          //     if (text === el.value) {
          //       txt = el.name
          //     }
          //   })
          //   return txt
          // }
          scopedSlots: {
            customRender: 'statusCustom'
          }
        },
        {
          title: '起止时间',
          align: 'center',
          ellipsis: true,
          dataIndex: 'startAndEndTime'
        },
        {
          title: '响应时间',
          align: 'center',
          ellipsis: true,
          dataIndex: 'responseTime'
        },
        {
          title: '操作',
          align: 'center',
          ellipsis: true,
          width: 100,
          scopedSlots: {
            customRender: 'operation'
          }
        }
      ],
      // 表数据
      data: [],
      // 表格loading
      tableLoading: false,
      // 分页配置
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页显示数量
        showQuickJumper: true, // 跳转
        showSizeChanger: true, // 显示改变每页数量
        total: 0, // 总数
        pageSizeOptions: ['10', '15', '20', '25'],
        showTotal: total => `共 ${total} 条` // 显示总数
      },
      // 选中行
      selectedRowKeys: [],
      // 是否打开查看方案
      viewVisible: false,
      // 查看方案抽屉id
      viewId: ''
    }
  },
  computed: {
    // 是否有选中项
    isSelecte () {
      return this.selectedRowKeys.length > 0
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    // table自定义事件
    tableCustomRow (record) {
      return {
        on: { // 事件
          dblclick: (event) => {
            this.view(record)
          }
        }
      }
    },
    edit (record) {
      this.$router.push({
        name: 'schemeStart',
        params: {
          mode: 'edit',
          id: record.id
        }
      })
    },
    // 初始化
    async init () {
      // 获取数据字典
      this.dataDictionary = await this.getDataDictionary()
      // 写入应急类型
      this.emergencyTypeList = this.dataDictionary['W-067']
      // 写入响应类型
      this.responseTypeList = this.dataDictionary['W-068']
      // 写入执行状态
      this.statusList = this.dataDictionary['W-069']
      this.pageReady = true
      // 查询数据
      this.searchData()
    },
    // 获取数据字典
    getDataDictionary () {
      return new Promise((resolve, reject) => {
        getDictData('W-067,W-068,W-069').then(res => {
          resolve(res.data)
        }).catch(error => {
          reject(error)
          console.log(error)
        })
      })
    },
    // 状态按钮
    handleStatus (status) {
      let txt = ''
      this.dataDictionary['W-069'].forEach(el => {
        if (status !== el.value) {
          txt = el.name
        }
      })
      return txt
    },
    // 查询数据
    searchData () {
      this.getScheme()
    },
    // 获取方案列表
    getScheme () {
      this.tableLoading = true
      let startTime = ''
      let endTime = ''
      let createStartTime = ''
      let createEndTime = ''
      if (this.searchForm.fromTo.length > 0) {
        startTime = this.$moment(this.searchForm.fromTo[0]).format('YYYY-MM-DD')
        endTime = this.$moment(this.searchForm.fromTo[1]).format('YYYY-MM-DD')
      }
      if (this.searchForm.createTime.length > 0) {
        createStartTime = this.$moment(this.searchForm.createTime[0]).format('YYYY-MM-DD')
        createEndTime = this.$moment(this.searchForm.createTime[1]).format('YYYY-MM-DD')
      }
      getPageHnPlan({
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        param: {
          name: this.searchForm.name,
          contingencyType: this.searchForm.emergencyType,
          startTime: startTime,
          endTime: endTime,
          createStartTime: createStartTime,
          createEndTime: createEndTime,
          responseType: this.searchForm.responseType,
          status: this.searchForm.status
        }
      }).then(res => {
        this.tableLoading = false
        if (res.code === '0') {
          this.data = res.data.list
        }
      }).catch(error => {
        console.log(error)
        this.tableLoading = false
      })
    },
    // 重置
    resetSearch () {
      this.searchForm = {}
    },
    // 选中行
    selectedRowChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 批量删除
    batchRemove () {
      this.$confirm({
        title: '你确定要删除此方案?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          deleteBatch(this.selectedRowKeys).then(res => {
            if (res.code === '0') {
              this.$message.success('删除成功!')
              this.searchData()
            } else {
              this.$message.success('删除失败!')
            }
          }).catch(error => {
            console.log(error)
            this.$message.success('删除失败!')
          })
        }
      })
    },
    // 修改方案状态
    upStatus (text, record, index) {
      let status = ''
      this.dataDictionary['W-069'].forEach(el => {
        console.log(record.status, el.value)
        if (record.status !== el.value) {
          status = el.value
        }
      })
      console.log(status)
      updateStatus({
        id: record.id,
        status: status
      }).then(res => {
        if (res.code === '0') {
          this.$message.success('操作成功!')
          this.searchData()
        } else {
          this.$message.success('操作失败!')
        }
      }).catch(error => {
        console.log(error)
        this.$message.success('操作失败!')
      })
    },
    // 表格变动
    tableChange (pagination, filters, sorter) {
      this.pagination = pagination
      // 查询接口
      this.searchData()
    },
    // 改变状态
    changeState () {

    },
    // 查看
    view (record) {
      this.viewVisible = true
      this.viewId = record.id
    },
    // 查看方案关闭
    handleViewVisible (parms) {
      this.viewVisible = parms
    }
  }
}
</script>
<style lang="scss">
// table {
//   table-layout: fixed;
// }
// table tr,
// table td {
//   text-overflow: ellipsis;
//   overflow: hidden;
//   white-space: nowrap;
// }
</style>
